#include "StdAfx.h"
#include "ClassFactory.h"
#include "Math.h"

unsigned long CClassFactory::m_cServerlock = 0;
CClassFactory::CClassFactory(void)
{
	m_cRef = 0;
	CClassFactory::m_cServerlock++;
}


CClassFactory::~CClassFactory(void)
{
	CClassFactory::m_cServerlock--;
}

HRESULT __stdcall CClassFactory::QueryInterface( const IID& riid, void **ppvObject )
{
	TraceMsg(L"CClassFactory::QueryInterface\n");
	if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
	{
		*ppvObject = static_cast<IClassFactory*>(this);
	}
	else
	{
		*ppvObject = NULL;
		return E_NOINTERFACE;
	}
	static_cast<IUnknown*>(*ppvObject)->AddRef();
	return S_OK;
}

ULONG __stdcall CClassFactory::AddRef()
{
	TraceMsg(L"CClassFactory::AddRef\n");
	return InterlockedIncrement(&m_cRef);
}

ULONG __stdcall CClassFactory::Release()
{
	TraceMsg(L"CClassFactory::Release\n");
	if (InterlockedDecrement(&m_cRef) == 0)
	{
		delete this;
		return 0;
	}
	return m_cRef;
}

HRESULT __stdcall CClassFactory::CreateInstance( IUnknown *pUnkOuter, REFIID riid, void **ppvObject )
{
	TraceMsg(L"CClassFactory::CreateInstance\n");
	if (pUnkOuter != NULL)
	{
		return E_NOINTERFACE;
	}
	CMath *pMath = new CMath();
	if (pMath == NULL)
	{
		return E_OUTOFMEMORY;
	}
	HRESULT hr = pMath->QueryInterface(riid, ppvObject);
// 	pMath->Release();
	return hr;
}

HRESULT __stdcall CClassFactory::LockServer( BOOL bLock )
{
	TraceMsg(L"CClassFactory::LockServer Lock:%d\n", bLock);
	if (bLock)
	{
		InterlockedIncrement(&m_cServerlock);
	}
	else
	{
		InterlockedDecrement(&m_cServerlock);
	}
	return S_OK;
}
